# -*- encoding: utf-8 -*-
##############################################################################
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see http://www.gnu.org/licenses/.
#
##############################################################################

from odoo import models, fields, api
from odoo.tools.translate import _
from odoo.exceptions import ValidationError
from odoo.tools.float_utils import float_round


class stock_production_lot(models.Model):
    _inherit = 'stock.production.lot'

    name = fields.Char(
        u'批次/序列号', readonly=True, default='New' + str(fields.datetime.now()),
        required=True, help="Unique Lot/Serial Number")

    ref = fields.Char(u'追踪号',
                      help="Internal reference number in case it differs from the manufacturer's lot/serial number")
    mrp_platform = fields.Char(u"机台号", size=20)
    mrp_shift = fields.Char(u"班次", size=20)
    remark_one = fields.Char(u"备注1", size=20)
    remark_two = fields.Char(u"备注2", size=20)

    @api.model
    def create(self, values):
        if not values.get('name', False) or 'New' in values['name']:
            values['name'] = self.env['ir.sequence'].next_by_code('stock.lot.serial') or _('New') + +str(
                fields.datetime.now())
        return super(stock_production_lot, self).create(values)

    lot_uom = fields.Many2one('product.uom', u'辅助单位')
    lot_uom_ratio = fields.Float(u'换算率', digits=(16, 4))
    lot_lenth = fields.Char(u'全长')

    code = fields.Char(u"代码", size=10)
    description = fields.Char(u"说明", size=20)
    board_number = fields.Char(u"内部参考", size=20)

    idle = fields.Boolean(u'呆滞', default=False)
    sale_type = fields.Selection([('0', u'内销'), ('1', u'外销')], u'销售类型')

    @api.onchange('lot_uom')
    def onchange_lot_uom(self):
        if self.lot_uom:
            self.lot_uom_ratio = self.lot_uom.factor_inv
            # if self.lot_uom.uom_type == 'bigger':
            #     self.lot_uom_ratio = self.lot_uom.factor
            # elif self.lot_uom.uom_type == 'smaller':
            #     self.lot_uom_ratio = 1 / self.lot_uom.factor
            # else:
            #     self.lot_uom_ratio = 1

    @api.multi
    def toggle_idle(self):
        for quant in self:
            if quant.idle:
                quant.idle = False
            else:
                quant.idle = True

    @api.multi
    def name_get(self):
        res = []
        for lot in self:
            if lot.code or lot.description or lot.board_number:
                name = lot.name + "("
                if lot.code:
                    name += lot.code
                name += ","
                if lot.description:
                    name += lot.description
                name += ","
                if lot.board_number:
                    name += lot.board_number
                name += ')'
            else:
                name = lot.name
            if lot.ref:
                name = lot.ref + "-" + name
            res.append((lot.id, name))
        return res


class stock_pack_operation_lot(models.Model):
    _inherit = 'stock.pack.operation.lot'

    picking_type = fields.Many2one('stock.picking.type', u'调拨类型')
    lot_for_copy = fields.Many2one('stock.production.lot', u'信息复制')
    lot_uom = fields.Many2one('product.uom', u'辅助单位')
    lot_uom_qty = fields.Float(u'辅助单位数量')
    lot_uom_ratio = fields.Float(u'换算率', digits=(16, 4))
    lot_lenth = fields.Char(u'全长')
    ref = fields.Char(u'追踪号')

    code = fields.Char(u"代码", size=10)
    description = fields.Char(u"说明", size=20)
    board_number = fields.Char(u"内部参考", size=20)

    # create_lot = fields.Boolean(u'创建批次',default=False)

    # @api.onchange('lot_uom')
    # def onchange_lot_uom(self):
    #     if self.lot_uom:
    #         self.lot_uom_ratio = self.lot_uom.factor_inv
            # if self.lot_uom.uom_type == 'bigger':
            #     self.lot_uom_ratio = self.lot_uom.factor
            # elif self.lot_uom.uom_type == 'smaller':
            #     self.lot_uom_ratio = 1 / self.lot_uom.factor
            # else:
            #     self.lot_uom_ratio = 1

    @api.onchange('lot_name')
    def onchange_lot_name(self):
        if self.lot_name and not self.lot_id:
            self.lot_name = None
        if self.lot_name and self.lot_id:
            self.lot_name = self.lot_id.display_name

    @api.onchange('lot_for_copy')
    def onchange_lot_for_copy(self):
        if self.lot_for_copy:
            self.lot_lenth = self.lot_for_copy.lot_lenth
            self.code = self.lot_for_copy.code
            self.description = self.lot_for_copy.description
            self.board_number = self.lot_for_copy.board_number
            self.lot_uom = self.lot_for_copy.lot_uom.id
            self.lot_uom_ratio = self.lot_for_copy.lot_uom_ratio
            self.ref = self.lot_for_copy.ref
            self.qty = self.lot_uom_qty * self.lot_uom_ratio
            # self.mrp_platform = self.lot_for_copy.mrp_platform
            # self.mrp_shift = self.lot_for_copy.mrp_shift
            # self.remark_one = self.lot_for_copy.remark_one
            # self.remark_two = self.lot_for_copy.remark_twoz

    @api.onchange('lot_id')
    def onchange_lot_id(self):
        if self.lot_id:
            self.lot_lenth = self.lot_id.lot_lenth
            self.code = self.lot_id.code
            self.description = self.lot_id.description
            self.board_number = self.lot_id.board_number
            self.lot_uom_ratio = self.lot_id.lot_uom_ratio
            self.lot_uom = self.lot_id.lot_uom.id

    @api.onchange('lot_uom_qty', 'lot_uom_ratio')
    def onchange_lot_uom_ratio(self):
        # if self.qty_todo>0 and self.operation_id.picking_id.picking_type.code=='outgoing':
        #     self.qty=self.qty_todo
        # else:
        self.qty = self.lot_uom_qty * self.lot_uom_ratio

    @api.onchange('lot_lenth', 'code', 'description', 'board_number')
    def onchange_something(self):
        if self.lot_id:
            self.lot_id.lot_lenth = self.lot_lenth
            self.lot_id.code = self.code
            self.lot_id.description = self.description
            self.lot_id.board_number = self.board_number

    @api.onchange('qty')
    def onchange_qty(self):
        if not self.lot_id and self.qty > 0:
            lot_id = self.env['stock.production.lot'].create({
                'product_id': self.operation_id.product_id.id,
                # 字段赋值
                'lot_uom': self.lot_uom.id,
                'lot_uom_ratio': self.lot_uom_ratio,
                'lot_lenth': self.lot_lenth,
                'ref': self.ref,
                'code': self.code,
                'description': self.description,
                'board_number': self.board_number,
            })
            self.lot_id = lot_id
            self.lot_name = lot_id.display_name
            #
            # @api.model
            # def create_lot_for_pack(self, fields):
            #     res = super(stock_pack_operation_lot, self).default_get(fields)
            #     if 'operation_id' not in res and res.get('operation_id'):
            #         pack = self.env['stock.pack.operation'].search([('operation_id', '=', res['operation_id'])], limit=1)
            #     if pack and not res.get('lot_id'):
            #         lot_id = self.env['stock.production.lot'].create({
            #             'product_id': pack.product_id.id
            #         })
            #         res['lot_id'] = lot_id.id
            #         res['lot_name'] = lot_id.name
            #     return res
            #
            # @api.multi
            # def create_lot_for_pack(self):
            #     for pack_lot in self:
            #         if not pack_lot.lot_id:
            #             lot_id=self.env['stock.production.lot'].create({
            #                 'product_id': pack_lot.operation_id.product_id.id
            #             })
            #             pack_lot.lot_id =lot_id
            #             pack_lot.lot_name=lot_id.name
            #         else:
            #             raise ValidationError(u'已有批次号,不能重复生成!')
